﻿using BLL.Base;
using BLL.Basis;
using BLL.U8.CommonMethod;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BLL
{
    public partial class U8Service
    {
        /// <summary>
        /// 方法仅限同一日期，同一仓库，同一收发类别编码。如果不符合条件，结果不可知。
        /// 产成品入库
        /// </summary>
        /// <param name="tempList">需要入库的扫描临时表数据</param>
        /// <param name="code"></param>
        /// <param name="uscode"></param>
        /// <returns></returns>

        public ReturnResult AddProductIn(List<DbTempScanData> tempList, string code, string uscode)
        {
            if (tempList == null)
            {
                var sql = "select * from Test_View_TempData";
                var dt = command.GetDataTable(sql);
                tempList = DataConverter.ConvertDataTable<DbTempScanData>(dt);
                code = "00001";
                uscode = "admin";
            }


            rsl = new ReturnResult();
            try
            {
                //var tempViewList = TempViewTable(tempList);

                //if (tempViewList.Count == 0)
                //{
                //    rsl.Message = "单据数据不存在";
                //    return rsl;
                //}

                //var Inpars = new Dictionary<string, object>();
                //var pars = new Dictionary<string, object>();
                //pars["code"] = code;
                //pars["date"] = tempList[0].happenDate;
                //pars["marker"] = uscode;
                //pars["warehouse"] = tempList[0].wareHouse;
                //pars["receivecode"] = tempList[0].typeCode;

                //List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                //int js = 0;
                //foreach (var temp in tempViewList)
                //{
                //    var cpars = new Dictionary<string, object>();
                //    js++;
                //    cpars["inventorycode"] = temp.barCode;
                //    cpars["quantity"] = temp.number;
                //    cpars["rowno"] = js;

                //    clist.Add(cpars);
                //}
                //pars["entry"] = clist;
                //Inpars["productin"] = pars;

                //string url = Tools.ConfigReader.Reader["ProductInUrl"];
                //rsl = VisitAPI(url, Inpars);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 创建销售发票
        public ReturnResult CreateSaleInvoice(string json)
        {
            rsl = new ReturnResult();
            try
            {
                //var JObj = JsonConvert.DeserializeObject<JObject>(json);

                //var Main = new Dictionary<string, object>();
                //var Head = new Dictionary<string, object>();

                //Head["vouchertype"] = JObj["saleinvoice"]["vouchertype"];
                //Head["saletypecode"] = JObj["saleinvoice"]["saletypecode"];
                //Head["date"] = JObj["saleinvoice"]["date"];
                //Head["departmentcode"] = JObj["saleinvoice"]["departmentcode"];
                //Head["customercode"] = JObj["saleinvoice"]["customercode"];
                //Head["cSaleOut"] = JObj["saleinvoice"]["cSaleOut"];
                //Head["cSOCode"] = JObj["saleinvoice"]["cSOCode"];
                //Head["cDLCode"] = JObj["saleinvoice"]["cDLCode"];
                //Head["cCusName"] = JObj["saleinvoice"][""];
                ////Head["ccusbank"] = "保定支行";
                ////Head["cbaccount"] = "9800031344000";

                //var Body = new List<Dictionary<string, object>>();

                //var BodyPart = new Dictionary<string, object>();
                //BodyPart["warehousecode"] = "01";
                //BodyPart["inventorycode"] = "0101040001";
                //BodyPart["quantity"] = "-1";

                //Body.Add(BodyPart);

                //Main["saleinvoice"] = Head;
                //Head["entry"] = Body;

                string url = Tools.ConfigReader.Reader["invoiceUrl"];
                rsl = VisitAPI_PureJson(url, json);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 审核一张发货单
        //public ReturnResult VerifyConsignment(string json)
        //{
        //    rsl = new ReturnResult();
        //    try
        //    {

        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //}
    }

    public partial class U8Service
    {
        // 从临时数据视图中，查找对应临时码信息
        //public List<ViewU8ProductTempData> TempViewTable(List<DbTempScanData> tempList)
        //{
        //    // 查找记录
        //    var bigtempStr = "";
        //    foreach (var scanData in tempList)
        //    {
        //        bigtempStr += "'" + scanData.tempCode + "',";
        //    }
        //    bigtempStr = bigtempStr.Trim(',');

        //    var sql = "select * from V_U8_Protocol_TempDataInfo where tempCode in ( " + bigtempStr + ")";

        //    var dt = command.GetDataTable(sql);
        //    var uList = DataConverter.ConvertDataTable<ViewU8ProductTempData>(dt);

        //    var group = uList.GroupBy(x => new { x.proCode, x.spec });

        //    var reList = new List<ViewU8ProductTempData>();

        //    foreach (var ig in group)
        //    {
        //        var igFirst = ig.FirstOrDefault();
        //        igFirst.number = ig.Sum(x => decimal.Parse(x.number)).ToString();
        //        reList.Add(igFirst);
        //    }

        //    // 聚合
        //    return reList;
        //}
    }

    /// <summary>
    /// U8接口服务(OpenAPI)
    /// </summary>
    public partial class U8Service
    {
        HttpAgreement http;
        Commands command;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        BaseDataBLL baseBLL;
        public U8Service()
        {
            http = new HttpAgreement();
            command = new Commands();
            txt = new Tools.TxtLogHelper();
            baseBLL = new BaseDataBLL();
        }
        string fromAccount = Tools.ConfigReader.Reader["fromAccount"];
        string toAccount = Tools.ConfigReader.Reader["to_account"];
        string appkey = Tools.ConfigReader.Reader["app_key"];
        string appsecret = Tools.ConfigReader.Reader["app_secret"];
        string token = string.Empty;
        /// <summary>
        /// 其他入库
        /// </summary>
        /// <param name="tempList">提交数据</param>
        /// <param name="code">编码</param>
        /// <param name="usCode">制单人</param>
        /// <returns></returns>
        public ReturnResult AddOtherIn(List<DbTempScanData> tempList, string code, string usCode)
        {
            rsl = new ReturnResult();
            try
            {
                var orderTable = this.orderTable(tempList[0].tempCode);
                if (orderTable == null || orderTable.Rows.Count < 1)
                {
                    rsl.Message = "单据数据不存在";
                    return rsl;
                }

                #region 业务逻辑代码
                var Inpars = new Dictionary<string, object>();
                #region 其他入库单表头字段参数
                var pars = new Dictionary<string, object>();
                pars["code"] = code;//单据号
                pars["date"] = tempList[0].happenDate;//发生日期
                pars["marker"] = usCode;
                pars["warehousecode"] = tempList[0].wareHouse;
                pars["receivecode"] = tempList[0].typeCode;

                #endregion

                #region 表体参数
                List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                int js = 0;
                foreach (DataRow row in orderTable.Rows)
                {
                    var cpars = new Dictionary<string, object>();
                    js++;
                    cpars["inventorycode"] = row["proCode"].ToString();
                    cpars["quantity"] = row["weight"].ToString();
                    cpars["rowno"] = js;
                    //var jg = baseBLL.getProductPriceByCode(row["proCode"].ToString());
                    //if (jg == "0")
                    //{
                    //    rsl.Message = string.Format("存货无价格信息:{0}", row["proCode"].ToString());
                    //    return rsl;
                    //}
                    //else
                    //{
                    //    cpars["price"] = jg;
                    //    cpars["cost"] = double.Parse(row["weight"].ToString()) * double.Parse(jg);
                    //}
                    clist.Add(cpars);
                }
                pars["entry"] = clist;
                #endregion
                Inpars["otherin"] = pars;
                #endregion
                string url = Tools.ConfigReader.Reader["OtherInUrl"];//其他入库单接口地址 https://api.yonyouup.com/api/otherin/add
                rsl = VisitAPI(url, Inpars);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 其他出库
        /// </summary>
        /// <param name="tempList">扫描数据</param>
        /// <returns></returns>
        public ReturnResult AddOtherOut(List<DbTempScanData> tempList, string code, string usCode)
        {
            rsl = new ReturnResult();
            try
            {
                var orderTable = this.orderTable(tempList[0].tempCode);
                if (orderTable == null || orderTable.Rows.Count < 1)
                {
                    rsl.Message = "单据数据不存在";
                    return rsl;
                }

                #region 业务逻辑代码
                var Inpars = new Dictionary<string, object>();
                #region 其他入库单表头字段参数
                var pars = new Dictionary<string, object>();
                pars["code"] = code;//单据号
                pars["date"] = tempList[0].happenDate;//发生日期
                pars["marker"] = usCode;
                pars["warehousecode"] = tempList[0].wareHouse;
                pars["receivecode"] = tempList[0].typeCode;

                #endregion

                #region 表体参数
                List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                int js = 0;
                foreach (DataRow row in orderTable.Rows)
                {
                    var cpars = new Dictionary<string, object>();
                    js++;
                    cpars["inventorycode"] = row["proCode"].ToString();
                    cpars["quantity"] = row["weight"].ToString();
                    cpars["rowno"] = js;
                    //var jg = baseBLL.getProductPriceByCode(row["proCode"].ToString());
                    //if (jg == "0")
                    //{
                    //    rsl.Message = string.Format("存货无价格信息:{0}", row["proCode"].ToString());
                    //    return rsl;
                    //}
                    //else
                    //{
                    //    cpars["price"] = jg;
                    //    cpars["cost"] = double.Parse(row["weight"].ToString()) * double.Parse(jg);
                    //}
                    clist.Add(cpars);
                }
                pars["entry"] = clist;
                #endregion
                Inpars["otherout"] = pars;
                #endregion
                string url = Tools.ConfigReader.Reader["OtherOutUrl"];//其他入库单接口地址 https://api.yonyouup.com/api/otherout/add
                rsl = VisitAPI(url, Inpars);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 发货单
        /// </summary>
        /// <param name="tempList"></param>
        /// <returns></returns>
        public ReturnResult SalesOut(List<DbTempScanData> tempList, string code)
        {
            rsl = new ReturnResult();
            try
            {
                #region 组建数据
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull(proCode,'') proCode,barCode,");
                sb.Append(" isnull(number,'0') number from bar_ProductBarCode_info where ");
                sb.Append(" barCode in (select barCode from bar_TempScanData_info where  ");
                sb.Append("tempCode='" + tempList[0].tempCode + "')");
                var table = command.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                DataTable oTable = new DataTable();
                oTable.Columns.Add("proCode");
                oTable.Columns.Add("weight");
                oTable.Columns.Add("price");


                StringBuilder pf = new StringBuilder();
                pf.Append("select wholePrice,retailPrice,proCode ");
                pf.Append(" from fun_productPrice_info where ");
                pf.Append("isdel=0");
                var priceTable = command.GetDataTable(pf.ToString());//获取全部价格信息

                sb.Clear();
                sb.Append("select cuType from fun_Customs_info");
                sb.Append(" where cuCode='" + tempList[0].customCode + "'");//获取客户类型
                var cuTable = command.GetDataTable(sb.ToString());
                if (cuTable.Rows.Count < 1)
                {
                    rsl.Message = "客户信息丢失";
                    return rsl;
                }

                #region 填充数据
                foreach (DataRow r in table.Rows)
                {
                    if (!reList.Contains(r["proCode"].ToString()))
                    {
                        DataRow row = oTable.NewRow();
                        row["proCode"] = r["proCode"].ToString();
                        row["weight"] = r["number"].ToString();
                        var dr = priceTable.Select("proCode='" + r["proCode"].ToString() + "'");
                        #region 价格信息
                        if (cuTable.Rows[0]["cuType"].ToString() == "pifa")
                        {
                            if (dr.Length > 0)
                            {
                                row["price"] = dr[0]["wholePrice"].ToString();
                            }
                            else
                            {
                                row["price"] = "0";
                            }
                        }
                        else
                        {
                            if (dr.Length > 0)
                            {
                                row["price"] = dr[0]["retailPrice"].ToString();
                            }
                            else
                            {
                                row["price"] = "0";
                            }
                        }
                        #endregion
                        oTable.Rows.Add(row);
                        reList.Add(r["proCode"].ToString());
                    }
                    else
                    {
                        for (int i = 0; i < oTable.Rows.Count; i++)
                        {
                            if (oTable.Rows[i]["proCode"].ToString() == r["proCode"].ToString())
                            {
                                oTable.Rows[i]["weight"] = Convert.ToString(double.Parse(r["number"].ToString()) + double.Parse(oTable.Rows[i]["weight"].ToString()));
                                break;
                            }
                        }
                    }
                }
                #endregion

                #endregion
                if (oTable == null || oTable.Rows.Count < 1)
                {
                    rsl.Message = "单据数据不存在";
                    return rsl;
                }

                #region 业务逻辑代码


                var Inpars = new Dictionary<string, object>();
                #region 表头字段参数
                var pars = new Dictionary<string, object>();
                pars["code"] = code;//单据号
                pars["date"] = tempList[0].happenDate;//发生日期
                pars["marker"] = tempList[0].createuser;
                pars["custcode"] = tempList[0].customCode;//客户信息
                pars["deptcode"] = tempList[0].operateDept;//部门编码

                #endregion

                #region 表体参数
                List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                foreach (DataRow row in oTable.Rows)
                {
                    var cpars = new Dictionary<string, object>();
                    cpars["warehouse_code"] = tempList[0].wareHouse;//仓库信息
                    cpars["inventory_code"] = row["proCode"].ToString();//存货编码
                    cpars["quantity"] = row["weight"].ToString();//数量
                    var jg = row["price"].ToString();
                    if (jg == "0")
                    {
                        rsl.Message = string.Format("存货无价格信息:{0}", row["proCode"].ToString());
                        return rsl;
                    }
                    else
                    {
                        cpars["price"] = jg;//单价
                    }
                    clist.Add(cpars);
                }
                pars["entry"] = clist;
                #endregion
                Inpars["consignment"] = pars;
                #endregion
                rsl = VisitAPI(Tools.ConfigReader.Reader["saleOrder"], Inpars);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 调拨单
        /// </summary>
        /// <param name="tempList"></param>
        /// <returns></returns>
        public ReturnResult proAllocation(List<DbTempScanData> tempList, string code)
        {
            rsl = new ReturnResult();
            try
            {
                #region 组建数据
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull(proCode,'') proCode,barCode,");
                sb.Append(" isnull(number,'0') number from bar_ProductBarCode_info where ");
                sb.Append(" barCode in (select barCode from bar_TempScanData_info where  ");
                sb.Append("tempCode='" + tempList[0].tempCode + "')");
                var table = command.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                DataTable oTable = new DataTable();
                oTable.Columns.Add("proCode");
                oTable.Columns.Add("weight");
                oTable.Columns.Add("price");

                #region 填充数据
                foreach (DataRow r in table.Rows)
                {
                    if (!reList.Contains(r["proCode"].ToString()))
                    {
                        DataRow row = oTable.NewRow();
                        row["proCode"] = r["proCode"].ToString();
                        row["weight"] = r["number"].ToString();
                        oTable.Rows.Add(row);
                        reList.Add(r["proCode"].ToString());
                    }
                    else
                    {
                        for (int i = 0; i < oTable.Rows.Count; i++)
                        {
                            if (oTable.Rows[i]["proCode"].ToString() == r["proCode"].ToString())
                            {
                                oTable.Rows[i]["weight"] = Convert.ToString(double.Parse(r["number"].ToString()) + double.Parse(oTable.Rows[i]["weight"].ToString()));
                                break;
                            }
                        }
                    }
                }
                #endregion

                #endregion
                if (oTable == null || oTable.Rows.Count < 1)
                {
                    rsl.Message = "单据数据不存在";
                    return rsl;
                }

                #region 业务逻辑代码

                var Inpars = new Dictionary<string, object>();
                #region 表头字段参数
                var pars = new Dictionary<string, object>();
                pars["tvcode"] = code;//单据号
                pars["date"] = tempList[0].happenDate;//发生日期
                //pars["personcode"] = tempList[0].createuser;//业务员
                pars["iwhcode"] = tempList[0].targetWareHouse;//转入仓库
                pars["owhcode"] = tempList[0].wareHouse;//转出仓库
                pars["irdcode"] = tempList[0].targetTypeCode;//入库类别
                pars["ordcode"] = tempList[0].typeCode;//出库类别
                pars["marker"] = tempList[0].createuser;
                // pars["idepcode"] = tempList[0].operateDept;//转入部门编码
                // pars["odepcode"] = tempList[0].operateDept;//转出部门编码
                #endregion

                #region 表体参数
                List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                int js = 0;
                foreach (DataRow row in oTable.Rows)
                {
                    js++;
                    var cpars = new Dictionary<string, object>();
                    cpars["irowno"] = js;//行号
                    cpars["inventorycode"] = row["proCode"].ToString();//存货编码
                    cpars["quantity"] = row["weight"].ToString();//数量
                    cpars["irate"] = "1";//换算率
                    //var jg = baseBLL.getProductPriceByCode(row["proCode"].ToString());
                    //if (jg == "0")
                    //{
                    //    rsl.Message = string.Format("存货无价格信息:{0}", row["proCode"].ToString());
                    //    return rsl;
                    //}
                    //else
                    //{
                    //    cpars["actualcost"] = jg;
                    //    cpars["actualprice"] = double.Parse(row["weight"].ToString()) * double.Parse(jg);
                    //}    
                    clist.Add(cpars);
                }
                pars["entry"] = clist;
                #endregion
                Inpars["transvouch"] = pars;
                #endregion

                rsl = VisitAPI(Tools.ConfigReader.Reader["transvouch"], Inpars);
                txt.AddLogMsg("调拨单" + JsonConvert.SerializeObject(rsl.Data));
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 创建销售发票
        /// </summary>
        /// <param name="tempList"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public ReturnResult saleinVoice(List<DbTempScanData> tempList, string code)
        {
            rsl = new ReturnResult();
            try
            {
                #region 组建数据
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull(proCode,'') proCode,barCode,");
                sb.Append(" isnull(number,'0') number from bar_ProductBarCode_info where ");
                sb.Append(" barCode in (select barCode from bar_TempScanData_info where ");
                sb.Append("tempCode='" + tempList[0].tempCode + "')");
                var table = command.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                DataTable oTable = new DataTable();
                oTable.Columns.Add("proCode");
                oTable.Columns.Add("weight");
                oTable.Columns.Add("price");


                StringBuilder pf = new StringBuilder();
                pf.Append("select wholePrice,retailPrice,proCode ");
                pf.Append(" from fun_productPrice_info where ");
                pf.Append("isdel=0");
                var priceTable = command.GetDataTable(pf.ToString());//获取全部价格信息

                sb.Clear();
                sb.Append("select cuType from fun_Customs_info");
                sb.Append(" where cuCode='" + tempList[0].customCode + "'");//获取客户类型
                var cuTable = command.GetDataTable(sb.ToString());
                if (cuTable.Rows.Count < 1)
                {
                    rsl.Message = "客户信息丢失";
                    return rsl;
                }

                #region 填充数据
                foreach (DataRow r in table.Rows)
                {
                    if (!reList.Contains(r["proCode"].ToString()))
                    {
                        DataRow row = oTable.NewRow();
                        row["proCode"] = r["proCode"].ToString();
                        row["weight"] = r["number"].ToString();
                        var dr = priceTable.Select("proCode='" + r["proCode"].ToString() + "'");
                        #region 价格信息
                        if (cuTable.Rows[0]["cuType"].ToString() == "pifa")
                        {
                            if (dr.Length > 0)
                            {
                                row["price"] = dr[0]["wholePrice"].ToString();
                            }
                            else
                            {
                                row["price"] = "0";
                            }
                        }
                        else
                        {
                            if (dr.Length > 0)
                            {
                                row["price"] = dr[0]["retailPrice"].ToString();
                            }
                            else
                            {
                                row["price"] = "0";
                            }
                        }
                        #endregion
                        oTable.Rows.Add(row);
                        reList.Add(r["proCode"].ToString());
                    }
                    else
                    {
                        for (int i = 0; i < oTable.Rows.Count; i++)
                        {
                            if (oTable.Rows[i]["proCode"] == r["proCode"].ToString())
                            {
                                oTable.Rows[i]["weight"] = Convert.ToString(double.Parse(r["number"].ToString()) + double.Parse(oTable.Rows[i]["weight"].ToString()));
                                break;
                            }
                        }
                    }
                }
                #endregion

                #endregion
                if (oTable == null || oTable.Rows.Count < 1)
                {
                    rsl.Message = "单据数据不存在";
                    return rsl;
                }

                #region 业务逻辑代码


                var Inpars = new Dictionary<string, object>();
                #region 表头字段参数
                var pars = new Dictionary<string, object>();
                pars["date"] = tempList[0].happenDate;//发生日期
                                                      // pars["personcode"] = tempList[0].createuser;//支援编码
                pars["customercode"] = tempList[0].customCode;//客户
                pars["saletypecode"] = "00";//销售类型编号
                pars["cvouchertype"] = tempList[0].typeCode;//单据类型
                pars["departmentcode"] = tempList[0].operateDept;//部门编码
                #endregion

                #region 表体参数
                List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                foreach (DataRow row in oTable.Rows)
                {
                    var jg = row["price"].ToString();
                    if (jg == "0")
                    {
                        rsl.Message = string.Format("存货无价格信息:{0}", row["proCode"].ToString());
                        return rsl;
                    }
                    var cpars = new Dictionary<string, object>();
                    cpars["warehousecode"] = tempList[0].wareHouse;//仓库信息
                    cpars["inventorycode"] = row["proCode"].ToString();//存货编码
                    cpars["quantity"] = row["weight"].ToString();//数量
                    cpars["originalprice"] = row["price"].ToString();//无税单价
                    cpars["originaltaxedprice"] = row["price"].ToString();//含税单价
                    var jine = double.Parse(row["weight"].ToString()) * double.Parse(row["price"].ToString());//无税金额
                    cpars["originalmoney"] = jine;//无税金额
                    cpars["originaltax"] = "0";//税额
                    cpars["originalsum"] = jine;//价税合计
                    cpars["price"] = row["price"].ToString();//本币单价
                    cpars["tax"] = "0";//本币税额
                    cpars["sum"] = jine;//本币价税合计
                    cpars["taxrate"] = "0";//税率（%）
                    clist.Add(cpars);
                }
                pars["entry"] = clist;
                #endregion
                Inpars["saleinvoice"] = pars;
                #endregion
                rsl = VisitAPI(Tools.ConfigReader.Reader["invoiceUrl"], Inpars);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        // 访问接口的纯Json版本
        ReturnResult VisitAPI_PureJson(string apiUrl, string inputJson)
        {
            rsl = new ReturnResult();

            string token = this.createU8Token(fromAccount, appkey, appsecret);
            string url = string.Empty;
            string msg = this.getTradeId(fromAccount, appkey, token);
            string tradeId = string.Empty;
            if (!string.IsNullOrWhiteSpace(msg))
            {
                JObject obj = JObject.Parse(msg);
                if (!msg.ToLower().Contains("errcode"))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                tradeId = obj["trade"]["id"].ToString();
            }
            url = apiUrl;
            url = string.Format("{0}?from_account={1}&to_account={2}&app_key={3}&token={4}&tradeid={5}&ds_sequence=1", url, fromAccount, toAccount, appkey, token, tradeId);

            var info = this.RecResult_PureJson(url, inputJson);

            if (!string.IsNullOrWhiteSpace(info))
            {
                //如果返回的是30025错误码就更换tradeid
                if (info.Equals("continue"))
                {
                    VisitAPI_PureJson(apiUrl, inputJson);
                }
                msg = string.Format("U8接口调用记录：入参参数：{0},返回结果：{1},接口地址：{2}", inputJson, info, url);
                txt.AddLogMsg(msg);
                var json = JsonConvert.DeserializeObject<JObject>(info);
                if (json.Property("errcode") != null)
                {
                    rsl.Result = false;
                    rsl.Message = info;
                }
                else
                {
                    #region 接口没有返回错误编码
                    url = json["url"].ToString();
                    Thread.Sleep(3500);//接口要求最好休息2秒
                    info = http.Get(url, "");
                    if (!string.IsNullOrWhiteSpace(info))
                    {
                        json = JsonConvert.DeserializeObject<JObject>(info);

                        if (json.Property("errcode") == null)
                        {
                            if (json["ping_after"].ToString().Equals("3"))
                            {
                                rsl = VisitAPI_PureJson(apiUrl, inputJson);
                            }
                        }
                        if (json.Property("errcode") != null && json["errcode"].ToString() == "0")
                        {
                            rsl.Message = "成功";
                            rsl.Result = true;
                            rsl.Data = info;
                            return rsl;
                        }
                        else
                        {
                            rsl.Message = info;
                            return rsl;
                        }
                    }
                    else
                    {
                        rsl.Message = "接口错误";
                    }
                    #endregion
                }
            }
            else
            {
                rsl.Message = "接口返回结果为空";
            }
            return rsl;
        }

        int wcount_PureJson = 0;
        string RecResult_PureJson(string url, string inputJson)
        {
            wcount_PureJson++;
            if (wcount_PureJson > 2)
            {
                return "";
            }
            else
            {
                var info = http.PostJson(url, inputJson);
                if (info.Contains("30025"))
                {
                    return "continue";
                }
                else
                {
                    return info;
                }
            }
        }

        /// <summary>
        /// 访问API接口
        /// </summary>
        /// <param name="apiUrl">接口地址</param>
        /// <param name="pars">传递参数</param>
        /// <returns></returns>
        private ReturnResult VisitAPI(string apiUrl, Dictionary<string, object> pars)
        {
            rsl = new ReturnResult();

            string token = this.createU8Token(fromAccount, appkey, appsecret);
            string url = string.Empty;
            string msg = this.getTradeId(fromAccount, appkey, token);
            string tradeId = string.Empty;
            if (!string.IsNullOrWhiteSpace(msg))
            {
                JObject obj = JObject.Parse(msg);
                if (!msg.ToLower().Contains("errcode"))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                tradeId = obj["trade"]["id"].ToString();
            }
            url = apiUrl;
            url = string.Format("{0}?from_account={1}&to_account={2}&app_key={3}&token={4}&tradeid={5}&ds_sequence=1", url, fromAccount, toAccount, appkey, token, tradeId);

            var info = this.RecResult(url, pars);

            if (!string.IsNullOrWhiteSpace(info))
            {
                //如果返回的是30025错误码就更换tradeid
                if (info.Equals("continue"))
                {
                    VisitAPI(apiUrl, pars);
                }
                msg = string.Format("U8接口调用记录：入参参数：{0},返回结果：{1},接口地址：{2}", JsonConvert.SerializeObject(pars), info, url);
                txt.AddLogMsg(msg);
                var json = JsonConvert.DeserializeObject<JObject>(info);
                if (json.Property("errcode") != null)
                {
                    rsl.Result = false;
                    rsl.Message = info;
                }
                else
                {
                    #region 接口没有返回错误编码
                    url = json["url"].ToString();
                    Thread.Sleep(3500);//接口要求最好休息2秒
                    info = http.Get(url, "");
                    if (!string.IsNullOrWhiteSpace(info))
                    {
                        json = JsonConvert.DeserializeObject<JObject>(info);

                        if (json.Property("errcode") == null)
                        {
                            if (json["ping_after"].ToString().Equals("3"))
                            {
                                rsl = VisitAPI(apiUrl, pars);
                            }
                        }
                        if (json.Property("errcode") != null && json["errcode"].ToString() == "0")
                        {
                            rsl.Message = "成功";
                            rsl.Result = true;
                            rsl.Data = info;
                            return rsl;
                        }
                        else
                        {
                            rsl.Message = info;
                            return rsl;
                        }
                    }
                    else
                    {
                        rsl.Message = "接口错误";
                    }
                    #endregion
                }
            }
            else
            {
                rsl.Message = "接口返回结果为空";
            }
            return rsl;
        }

        int wcount = 0;
        private string RecResult(string url, Dictionary<string, object> dic)
        {
            wcount++;
            if (wcount > 2)
            {
                return "";
            }
            else
            {
                var json = JsonConvert.SerializeObject(dic);
                var info = http.PostJson(url, json);
                if (info.Contains("30025"))
                {
                    return "continue";
                }
                else
                {
                    return info;
                }
            }

        }
        private DataTable getBarInfoByCode(string barCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from bar_productstock_info where barcode='" + barCode + "'");
            return null;
        }
        /// <summary>
        /// 创建其他入库表
        /// </summary>
        /// <param name="tempCode">编码</param>
        /// <returns></returns>
        private DataTable orderTable(string tempCode)
        {
            try
            {
                #region 组建数据
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull(proCode,'') proCode,barCode,");
                sb.Append(" isnull(number,'0') number from bar_ProductBarCode_info where ");
                sb.Append(" barCode in (select barCode from bar_TempScanData_info where  ");
                sb.Append("tempCode='" + tempCode + "')");
                var table = command.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                DataTable oTable = new DataTable();
                oTable.Columns.Add("proCode");
                oTable.Columns.Add("weight");
                oTable.Columns.Add("price");
                sb.Append("");
                foreach (DataRow r in table.Rows)
                {
                    if (!reList.Contains(r["proCode"].ToString()))
                    {
                        DataRow row = oTable.NewRow();
                        row["proCode"] = r["proCode"].ToString();
                        row["weight"] = r["number"].ToString();
                        // row["price"] =baseBLL.getProductPriceByCode(r["proCode"].ToString());
                        oTable.Rows.Add(row);
                        reList.Add(r["proCode"].ToString());
                    }
                    else
                    {
                        for (int i = 0; i < oTable.Rows.Count; i++)
                        {
                            if (oTable.Rows[i]["proCode"].ToString() == r["proCode"].ToString())
                            {
                                oTable.Rows[i]["weight"] = Convert.ToString(double.Parse(r["number"].ToString()) + double.Parse(oTable.Rows[i]["weight"].ToString()));
                                break;
                            }
                        }
                    }
                }
                #endregion
                return oTable;
            }
            catch (Exception ex)
            {
                string msg = string.Format("orderTable方法错误,编码：{0},错误消息:{1}", tempCode, ex.Message);
                txt.AddLogMsg(msg);
            }
            return null;
        }


        /// <summary>
        /// <summary>
        /// 获取tradeid
        /// </summary>
        /// <param name="fromAccount"></param>
        /// <param name="appkey"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string getTradeId(string fromAccount, string appkey, string token)
        {
            try
            {
                string url = Tools.ConfigReader.Reader["TagdeUrl"];// https://api.yonyouup.com/system/tradeid
                url = string.Format("{0}?&from_account={1}&app_key={2}&token={3}", url, fromAccount, appkey, token);
                string msg = http.Get(url, "");//获取tradeIDe
                return msg;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #region 生成U8接口所需的token
        /// <summary>
        /// 生成U8接口所需的token
        /// </summary>
        /// <param name="fromAccount"></param>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        private string createU8Token(string fromAccount, string appKey, string appSecret)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_U8Token order by createtime desc");
                var table = command.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    var count = table.Rows[0]["count"].ToString();//token使用此时(接口规定 token至多只允许使用2000次)
                    var time = table.Rows[0]["createtime"].ToString();//token生成时间(有效时间2小时)
                    if (int.Parse(count) > 1995 || DateTime.Parse(time).AddMinutes(115) < DateTime.Now)
                    {
                        return getToken(fromAccount, appKey, appSecret);
                    }
                    else
                    {
                        string sql = string.Format("update sys_U8Token set count={0} where token='{1}'", int.Parse(count) + 1, table.Rows[0]["token"].ToString());
                        command.UpdateSql(sql);
                        return table.Rows[0]["token"].ToString();
                    }
                }
                else
                {
                    return getToken(fromAccount, appKey, appSecret);
                }

            }
            catch (Exception ex)
            {

            }
            return "";
        }
        #endregion

        #region token获取
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="fromAccount"></param>
        /// <param name="appKey"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        private string getToken(string fromAccount, string appKey, string appSecret)
        {

            string url = Tools.ConfigReader.Reader["TokenUrl"];//https://api.yonyouup.com/system/token
            url = string.Format("{0}?from_account={1}&app_key={2}&app_secret={3}", url, fromAccount, appKey, appSecret);
            txt.AddLogMsg("获取token：" + url);
            string msg = http.Get(url, "");
            //string token = string.Empty;// http.Get(url, "");
            if (!string.IsNullOrWhiteSpace(msg))
            {
                var tjson = JsonConvert.DeserializeObject<JObject>(msg);
                if (tjson["errcode"].ToString() == "0")
                {
                    token = tjson["token"]["id"].ToString();
                    string sql = string.Format("insert into sys_U8Token (token,createtime,count) values('{0}','{1}',{2})", tjson["token"]["id"].ToString(), DateTime.Now.ToString(), "1");
                    command.UpdateSql(sql);
                }
            }
            return token;

        }
        #endregion



    }
}
